package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.common.AppConstants;
import co.gov.medellin.sdep.sisdep.common.OracleHelper;
import co.gov.medellin.sdep.sisdep.gestion.dto.VisitaAdministrativaDTO;
import co.gov.medellin.sdep.sisdep.model.CentroComercial;
import co.gov.medellin.sdep.sisdep.model.VisitaAdministrativa;

public class CentroComercialDAOImpl extends JdbcDaoSupport implements ICentroComercialDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;
    
    private ListaCentrosComerciales listaCco;
    
    private FindByNombreQuery findByNombreQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM CCO_CENTRO_COMERCIAL_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(CentroComercial centroComercial) {
		deleteOperation.execute( centroComercial  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public CentroComercial findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(CentroComercial centroComercial) {
		insertOperation.execute( centroComercial );
	}

	public void update(CentroComercial centroComercial) {
		updateOperation.execute( centroComercial );
	}

	public CentroComercial findByCriteria(CentroComercial  centroComercial) {
		return findByCriteriaQuery.runQuery(centroComercial);
	}

	public List load() {
		return findAllQuery.runQuery();
	}

	public List loadByNombre(CentroComercial centroComercial) {
		return findByNombreQuery.runQuery(centroComercial);
	}
	
	public List listaCentrosComerciales() {
		return listaCco.runQuery();
	}

	public CentroComercial findByActiveState(CentroComercial  centroComercial) {
		return findByActiveStateQuery.runQuery(centroComercial);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findByNombreQuery = new FindByNombreQuery( getDataSource() );
    	listaCco = new ListaCentrosComerciales(getDataSource());
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO CCO_CENTRO_COMERCIAL_T ("
				  + " ID, "
				  + " CODIGO, "
				  + " NOMBRE, "
				  + " NOMBRE_ADMINISTRADOR, "
				  + " TELEFONO, "
				  + " DIRECCION, "
				  + " COD_BARRIO, "
				  + " COD_COMUNA, "
				  + " BARRIO, "
				  + " COMUNA, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "			
				  + ") VALUES ("
			  	  + " CCO_CENTRO_COMERCIAL_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(CentroComercial centroComercial) {
			InsertOperation.this.update( new Object[]{			
				centroComercial.getCodigo(),
				centroComercial.getNombre(),
				centroComercial.getNombreAdministrador(),
				centroComercial.getTelefono(),
				centroComercial.getDireccion(),
				centroComercial.getCodBarrio(),
				centroComercial.getCodComuna(),
				centroComercial.getBarrio(),
				centroComercial.getComuna(),
				centroComercial.getEstado(),
				centroComercial.getUsuarioCrea()			
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE CCO_CENTRO_COMERCIAL_T SET "					  
					  + " CODIGO = ? ,"
					  + " NOMBRE = ? ,"
					  + " NOMBRE_ADMINISTRADOR = ? ,"
					  + " TELEFONO = ? ,"
					  + " DIRECCION = ? ,"
					  + " COD_BARRIO = ? ,"
					  + " COD_COMUNA = ? ,"
					  + " BARRIO = ? ,"
					  + " COMUNA = ? ,"
					  + " ESTADO = ? ,"					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE "
				  	  + WHERE
				  	  + " ID = ?";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(CentroComercial centroComercial) {
			UpdateOperation.this.update( new Object[]{				
				centroComercial.getCodigo(),
				centroComercial.getNombre(),
				centroComercial.getNombreAdministrador(),
				centroComercial.getTelefono(),
				centroComercial.getDireccion(),
				centroComercial.getCodBarrio(),
				centroComercial.getCodComuna(),
				centroComercial.getBarrio(),
				centroComercial.getComuna(),
				centroComercial.getEstado(),				
				centroComercial.getUsuarioModifica(),				
				centroComercial.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_CENTRO_COMERCIAL_T "
										+ WHERE
			  	  	  					+ " CODIGO = ? ";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
		}
		public void execute(CentroComercial centroComercial) {
			this.update( new Object[]{
				centroComercial.getCodigo(),
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_CENTRO_COMERCIAL_T "
										+ WHERE + "1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			CentroComercial centroComercial = new CentroComercial();
				centroComercial.setId(new Long(rs.getLong("ID")));
				centroComercial.setCodigo(rs.getString("CODIGO"));
				centroComercial.setNombre(rs.getString("NOMBRE"));
				centroComercial.setNombreAdministrador(rs.getString("NOMBRE_ADMINISTRADOR"));
				centroComercial.setTelefono(rs.getString("TELEFONO"));
				centroComercial.setDireccion(rs.getString("DIRECCION"));
				centroComercial.setCodBarrio(rs.getString("COD_BARRIO"));
				centroComercial.setCodComuna(rs.getString("COD_COMUNA"));
				centroComercial.setBarrio(rs.getString("BARRIO"));
				centroComercial.setComuna(rs.getString("COMUNA"));
				centroComercial.setEstado(rs.getString("ESTADO"));
				centroComercial.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				centroComercial.setFechaCrea(rs.getDate("FECHA_CREA"));		
				centroComercial.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				centroComercial.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return centroComercial;
		}
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ListaCentroComercialQueryOperation extends MappingSqlQuery {
		public ListaCentroComercialQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
				ArrayList typeValueList = new ArrayList();
				String registro[] = {"0","0"};
				registro[0]= rs.getString("ID");
				registro[1]= rs.getString("NOMBRE");
				typeValueList.add(registro);
				registro = null;
			return typeValueList;
		}
    }	
	
    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public CentroComercial runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (CentroComercial) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND CODIGO = ? "
			  	  	  					//+ " AND NOMBRE = ? "
			  	  	  					//+ " AND TELEFONO = ? "
			  	  	  					//+ " AND DIRECCION = ? "
			  	  	  					//+ " AND COD_BARRIO = ? "
			  	  	  					//+ " AND COD_COMUNA = ? "
			  	  	  					//+ " AND BARRIO = ? "
			  	  	  					//+ " AND COMUNA = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public CentroComercial runQuery(CentroComercial centroComercial) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//centroComercial.getId(),
				//centroComercial.getCodigo(),
				//centroComercial.getNombre(),
				//centroComercial.getTelefono(),
				//centroComercial.getDireccion(),
				//centroComercial.getCodBarrio(),
				//centroComercial.getCodComuna(),
				//centroComercial.getBarrio(),
				//centroComercial.getComuna(),
				//centroComercial.getEstado(),
				//centroComercial.getUsuarioCrea(),
				//centroComercial.getFechaCrea(),
				//centroComercial.getUsuarioModifica(),
				//centroComercial.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (CentroComercial) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =  execute();
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindByNombreQuery ----------------------------------------    
    class FindByNombreQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " UPPER(NOMBRE) like UPPER(?) ";
    	public FindByNombreQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(CentroComercial centroComercial) {
			List result = execute( new Object[]{
					"%"+centroComercial.getNombre()+"%"
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public CentroComercial runQuery(CentroComercial centroComercial) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (CentroComercial) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    class ListaCentrosComerciales extends ListaCentroComercialQueryOperation{
		private static final String sql = "SELECT ID,NOMBRE FROM CCO_CENTRO_COMERCIAL_T";
		public ListaCentrosComerciales(DataSource ds) {
					super(ds,sql);
					compile();
		}
		public List runQuery() {
				List result =  execute();
				if ( result.size() > 0 ) {
					return result;
				} else {
					return null;
				}
		}
    }
    
	public List generateXlsReportNumLocalesPorCCO() {
		
		StringBuffer query = new StringBuffer();
		ArrayList lista = new ArrayList();
	
		query.append("SELECT CCO.NOMBRE AS CENTRO_COMERCIAL,  CCO.NOMBRE_ADMINISTRADOR, COUNT(L.ID) AS NUMERO_LOCALES FROM ");
		query.append("CCO_LOCAL_T L INNER JOIN ");
		query.append("CCO_CENTRO_COMERCIAL_T CCO ON L.ID_CENTRO_COMERCIAL=CCO.ID ");		
		query.append("GROUP BY  CCO.NOMBRE,  CCO.NOMBRE_ADMINISTRADOR ");
		query.append("ORDER BY CCO.NOMBRE ASC");			
				
    	List rows = this.getJdbcTemplate().queryForList(query.toString());
		
    	Iterator iterator = rows.iterator();
    	
    	while (iterator.hasNext()) {
    		Map centroComercialMap = (Map) iterator.next();
        	CentroComercial centroComercialReport = new CentroComercial();	
    		centroComercialReport.setNombre(centroComercialMap.get("CENTRO_COMERCIAL").toString());
    		centroComercialReport.setNombreAdministrador(centroComercialMap.get("NOMBRE_ADMINISTRADOR").toString());
    		centroComercialReport.setNumeroLocales(centroComercialMap.get("NUMERO_LOCALES").toString());
    		lista.add(centroComercialReport);
    	}
		
		return lista;
	}    
	
	public List generateXlsReportNumLocalesDisponiblesPorCCO() {
		
		StringBuffer query = new StringBuffer();
		ArrayList lista = new ArrayList();
	
		query.append("SELECT CCO.NOMBRE AS CENTRO_COMERCIAL,  CCO.NOMBRE_ADMINISTRADOR, COUNT(LCCO.ID_LOCAL) AS NUMERO_LOCALES FROM ");
		query.append("CCO_LOCAL_T L INNER JOIN ");
		query.append("CCO_CENTRO_COMERCIAL_T CCO ON L.ID_CENTRO_COMERCIAL=CCO.ID ");	
		query.append("WHERE L.ESTADO = 'NO DISPONIBLE' ");		
		query.append("GROUP BY  CCO.NOMBRE,  CCO.NOMBRE_ADMINISTRADOR ");
		query.append("ORDER BY CCO.NOMBRE ASC");			
				
    	List rows = this.getJdbcTemplate().queryForList(query.toString());
		
    	Iterator iterator = rows.iterator();
    	
    	while (iterator.hasNext()) {
    		Map centroComercialMap = (Map) iterator.next();
        	CentroComercial centroComercialReport = new CentroComercial();	
    		centroComercialReport.setNombre(centroComercialMap.get("CENTRO_COMERCIAL").toString());
    		centroComercialReport.setNombreAdministrador(centroComercialMap.get("NOMBRE_ADMINISTRADOR").toString());
    		centroComercialReport.setNumeroLocales(centroComercialMap.get("NUMERO_LOCALES").toString());
    		lista.add(centroComercialReport);
    	}
		
		return lista;
	}  
	
	public List generateXlsReportLocalesPersonaPorCCO() {
		
		StringBuffer query = new StringBuffer();
		ArrayList lista = new ArrayList();
	
		query.append("SELECT CCO.NOMBRE AS CENTRO_COMERCIAL, L.NUMERO_LOCAL AS LOCAL_, ");
		query.append("(P.PRIMER_NOMBRE || ' ' || P.SEGUNDO_NOMBRE || ' ' || P.PRIMER_APELLIDO || ' ' || P.SEGUNDO_APELLIDO) AS PERSONA, ");
		query.append("VT.VRT_NOMBRE AS TIPO_DOCUMENTO, P.IDENTIFICACION AS DTO   FROM ");
		query.append("CCO_LOCAL_ENTREGA_T LE INNER JOIN ");
		query.append("CCO_LOCAL_T L ON LE.ID_LOCAL=L.ID INNER JOIN ");		
		query.append("CCO_CENTRO_COMERCIAL_T CCO ON L.ID_CENTRO_COMERCIAL=CCO.ID INNER JOIN ");		
		query.append("ADM_PERSONA_T P ON LE.ID_PERSONA = P.ID INNER JOIN ");
		query.append("ADM_VALOR_TIPO_MAESTRA_T VT ON P.ID_TIPO_IDENTIFICACION=VT.ID_VALOR_TIPO ");
		query.append("ORDER BY CCO.NOMBRE ASC, L.NUMERO_LOCAL ASC, P.PRIMER_APELLIDO ASC, P.SEGUNDO_APELLIDO ASC, P.PRIMER_NOMBRE ASC, P.SEGUNDO_NOMBRE ASC  ");
		
				
    	List rows = this.getJdbcTemplate().queryForList(query.toString());
		
    	Iterator iterator = rows.iterator();
    	
    	while (iterator.hasNext()) {
    		Map centroComercialMap = (Map) iterator.next();
        	CentroComercial centroComercialReport = new CentroComercial();	
    		centroComercialReport.setNombre(centroComercialMap.get("CENTRO_COMERCIAL").toString());
    		centroComercialReport.setNombreLocal(centroComercialMap.get("LOCAL_").toString());
    		centroComercialReport.setPersonaLocal(centroComercialMap.get("PERSONA").toString());
    		centroComercialReport.setTipoDtoPersonaLocal(centroComercialMap.get("TIPO_DOCUMENTO").toString());
    		centroComercialReport.setDtoPersonaLocal(centroComercialMap.get("DTO").toString());
    		lista.add(centroComercialReport);
    	}
		
		return lista;
	}  	
	
	public List generateXlsReportLocalesDisponiblesPorCCO() {
		
		StringBuffer query = new StringBuffer();
		ArrayList lista = new ArrayList();
	
		query.append("SELECT CCO.NOMBRE AS CENTRO_COMERCIAL,  CCO.NOMBRE_ADMINISTRADOR, L.NUMERO_LOCAL AS NUMERO_LOCAL FROM ");
		query.append("CCO_LOCAL_T L INNER JOIN ");
		query.append("CCO_CENTRO_COMERCIAL_T CCO ON L.ID_CENTRO_COMERCIAL=CCO.ID ");		
		query.append("WHERE L.ESTADO = 'NO DISPONIBLE' ");		
		query.append("GROUP BY  CCO.NOMBRE,  CCO.NOMBRE_ADMINISTRADOR,L.NUMERO_LOCAL ");
		query.append("ORDER BY CCO.NOMBRE ASC,L.NUMERO_LOCAL ASC");			
				
    	List rows = this.getJdbcTemplate().queryForList(query.toString());
		
    	Iterator iterator = rows.iterator();
    	
    	while (iterator.hasNext()) {
    		Map centroComercialMap = (Map) iterator.next();
        	CentroComercial centroComercialReport = new CentroComercial();	
    		centroComercialReport.setNombre(centroComercialMap.get("CENTRO_COMERCIAL").toString());
    		centroComercialReport.setNombreAdministrador(centroComercialMap.get("NOMBRE_ADMINISTRADOR").toString());
    		centroComercialReport.setNombreLocal(centroComercialMap.get("NUMERO_LOCAL").toString());
    		lista.add(centroComercialReport);
    	}
		
		return lista;
	}  	
}
